import Taro from '@tarojs/taro';
import {Image, View, Text, Textarea, Canvas} from '@tarojs/components';
import {connect} from "@tarojs/redux";
import {AtInput} from 'taro-ui';
import {appConfig, request, unite} from '../../../utils/index';
import {actionCreator} from "../../../store/actions";
import './issuePage.scss';
import ImgAdd from "../../../asset/images/img_add.png";
import Close from "../../../asset/images/close.png";
import Right from "../../../asset/images/right.png";
import Right1 from "../../../asset/images/right1.png";
import Address from "../../../asset/images/address_icon.png";
import Shop from "../../../asset/images/add_shop.png";

class IssuePage extends Taro.Component {
    config = {
        navigationBarTitleText: '发布',
        backgroundColor: '#fff',
    };

    state = {
        cWidth: 0, //canvas宽
        cHeight: 0, //canvas高

        imgData: [], //图片数组
        imgDataSl: [], //图片提前显示缩略图
        text: '', //图片标题
        title: '', //正文
        myCourse: [], //我的课程
        loadtion: [], //位置
    };

    temp = {
        isLoading: false,  //防止多次上拉刷新加载
        failNum: 0 ,//上传失败数量
        num: 0, //上传张数
        packImg: [], //存储压缩图片容器
        tempFilePath: [], //上传（图片）
    };

    componentDidShow() {
        const {gainCourse} = this.props;
        if (gainCourse) { //获取选中的课程
            this.setState({
                myCourse: gainCourse
            })
        }
    }

    componentWillMount() {
        const option = this.$router.params;
        const {userToken} = this.props;
        if (option.imgData) {
            var imgDa = option.imgData.split(',');
            console.log(JSON.stringify(typeof imgDa + 'imgDa'));

            //提前存储缩略图
            this.setState({
                imgDataSl: imgDa
            });
            this.temp.tempFilePath = imgDa;
            this.chkImg();


            // var imgs = [];
            // this.temp.failNum = 0; //失败张数归0
            // this.temp.tempFilePath = [];
            // this.temp.packImg = [];
            // this.temp.num = Number(imgDa.length);
            // for(let i = 0;i<imgDa.length;i++) {
            //     //5242880
            //     //判断证件大于7M时不执行
            //     if(imgDa[i].size > 7340032) {
            //         unite.showTipModal(`第${i+1}张图片太大了`);
            //         this.temp.num -= 1; //上传数量减1
            //         continue
            //     }
            //     Taro.getImageInfo({
            //         src: imgDa[i],
            //         success: (data) => {
            //             //判断证件大小小于宽度并且为上传手持身份证照时执行, 否则压缩证件
            //             let widthHeight = unite.imgZoom(data.width, data.height); //利用canvas压缩图片
            //             //----------绘制图形并取出图片路径--------------
            //             this.temp.packImg.push({ //存储要压缩的图片
            //                 widthHeight: widthHeight,
            //                 url: imgDa[i]
            //             });
            //             //当压缩图片数量等于数量时执行压缩
            //             if (this.temp.num == this.temp.packImg.length) {
            //                 //  图片长宽   图片路径  压缩张数索引值
            //                 this.setCanvas(this.temp.packImg[0].widthHeight, this.temp.packImg[0].url, 0);
            //             }
            //             // this.setCanvas(widthHeight, res.tempFilePaths[i]);  //Taro.canvasToTempFilePath   Canvas 在子组件中存在bug，所以提到父组件压缩
            //         }
            //     })
            // }







            // imgDa.forEach((item) => {
            //     Taro.uploadFile({
            //         url: 'https://pro.pmad.com.cn/api/momments/uploadMomentImg',
            //         filePath: item,
            //         name: 'avatarfile',
            //         fileType: 'image',
            //         accessToken: userToken,
            //         formData: {
            //             accessToken: userToken,
            //             avatarfile: item
            //         },
            //         success: (ret) => {
            //             let data = ret.data ? JSON.parse(ret.data) : {};
            //             console.log(JSON.stringify(data.data))
            //             if (data.code == 200) {
            //                 imgs.push(data.data);
            //                 if (imgs.length == (imgDa.length - this.temp.failNum)) {
            //                     this.setState({
            //                         imgData: imgs,
            //                     }, () => {})
            //                 }
            //             } else {
            //                 this.temp.failNum += 1; //失败张数加1
            //                 if (imgs.length == (imgDa.length - this.temp.failNum)) {
            //                     this.setState({
            //                         imgData: imgs,
            //                     }, () => {})
            //                 }
            //                 unite.showToast('图片错误请重新上传')
            //             }
            //         },
            //         fail: (e) => {
            //             console.log(e);
            //         }
            //     });
            // });
        }

    }

    componentWillUnmount() {
        const {getGainCourse} = this.props;
        getGainCourse('');
        Taro.switchTab({
            url: '/pages/home/home'
        })
    };

    temp = {
        isLoading: false  //防止多次上拉刷新加载
    };

    //上传图片
    upImgs = () => {
        const {imgData} = this.state;
        Taro.chooseImage({
            count: 9 - Number(imgData.length), //上传张数为1
            sizeType: ['original', 'compressed'],
            sourceType: ['album'],
            success: (res) => {
                if (res) {
                    this.temp.tempFilePath = [];
                    this.temp.packImg = [];
                    this.temp.num = Number(res.tempFilePaths.length);

                    //提前存储缩略图
                    this.setState(prevState => ({
                        imgDataSl: prevState.imgDataSl.concat(res.tempFilePaths)
                    }));

                    this.temp.tempFilePath = res.tempFilePaths;
                    this.chkImg();


                    // for(let i = 0;i<res.tempFilePaths.length;i++) {
                    //     //5242880
                    //     //判断证件大于7M时不执行
                    //     if(res.tempFiles[i].size > 7340032) {
                    //         unite.showTipModal(`第${i+1}张图片太大了`);
                    //         this.temp.num -= 1; //上传数量减1
                    //         continue
                    //     }
                    //     Taro.getImageInfo({
                    //         src: res.tempFilePaths[i],
                    //         success: (data) => {
                    //             //判断证件大小小于宽度并且为上传手持身份证照时执行, 否则压缩证件
                    //             let widthHeight = unite.imgZoom(data.width, data.height); //利用canvas压缩图片
                    //             //----------绘制图形并取出图片路径--------------
                    //             this.temp.packImg.push({ //存储要压缩的图片
                    //                 widthHeight: widthHeight,
                    //                 url: res.tempFilePaths[i]
                    //             });
                    //             //当压缩图片数量等于数量时执行压缩
                    //             if (this.temp.num == this.temp.packImg.length) {
                    //                 //  图片长宽   图片路径  压缩张数索引值
                    //                 this.setCanvas(this.temp.packImg[0].widthHeight, this.temp.packImg[0].url, 0);
                    //             }
                    //             // this.setCanvas(widthHeight, res.tempFilePaths[i]);  //Taro.canvasToTempFilePath   Canvas 在子组件中存在bug，所以提到父组件压缩
                    //         }
                    //     })
                    // }
                }
            },
            fail: () => {
            }
        })
    };

    //压缩证件
    setCanvas = (widthHeight, value, ix) => {
        //  widthHeight图片长宽   value图片路径  ix压缩张数索引值
        const {cWidth, cHeight} = this.state;
        Taro.showLoading({
            title: '图片压缩中...' //加载框
        });
        let ctx = Taro.createCanvasContext('myCanvas', this.$scope);
        ctx.clearRect(0, 0, cWidth, cHeight); //清空画布
        this.setState({
            cWidth:widthHeight.canvasWidth, //赋值压缩后的宽度
            cHeight: widthHeight.canvasHeight //赋值压缩后的高度
        });
        ctx.drawImage(value, 0, 0, widthHeight.canvasWidth, widthHeight.canvasHeight);
        setTimeout(() => {
            ctx.draw(true, () => {
                console.log('zhao');
                Taro.canvasToTempFilePath({
                    canvasId: 'myCanvas',
                    destWidth: widthHeight.canvasWidth,
                    destHeight: widthHeight.canvasHeight,
                    quality: 0.2,
                    fileType:'jpg',
                    success: (datas) => {
                        console.log(JSON.stringify(datas.tempFilePath) + 'zhao');
                        this.temp.tempFilePath.push(datas.tempFilePath);
                        if (this.temp.tempFilePath.length == this.temp.num) {
                            Taro.hideLoading();
                            this.chkImg()
                        } else {
                            this.setCanvas(this.temp.packImg[ix+1].widthHeight, this.temp.packImg[ix+1].url, (ix+1));
                        }
                        // this.chkImg(datas.tempFilePath);
                        console.log(JSON.stringify(this.temp.tempFilePath) + 'this.temp.tempFilePath');
                        console.log(JSON.stringify(this.temp.num) + 'this.temp.num');
                    },
                    fail: () => {
                        unite.showTipModal(`第${ix+1}张图片上传失败`);
                        this.temp.num -= 1;
                        if (this.temp.tempFilePath.length == this.temp.num) {
                            Taro.hideLoading();
                            this.chkImg()
                        }
                    },
                    complete: (datas) => {
                        console.log(datas);
                    },
                })
            });   //留一定的时间绘制canvas
            // clearTimeout(clear);
        }, 1000);
    };

    chkImg = () => {
        const {imgData} = this.state;
        const {userToken} = this.props;
        var imgs = [];
        this.temp.failNum = 0; //失败张数归0
        this.temp.tempFilePath.forEach((item, index) => {
            Taro.uploadFile({
                url: 'https://pro.pmad.com.cn/api/momments/uploadMomentImg',
                filePath: item,
                name: 'avatarfile',
                fileType: 'image',
                accessToken: userToken,
                formData: {
                    accessToken: userToken,
                    avatarfile: item
                },
                success: (ret) => {
                    let data = ret.data ? JSON.parse(ret.data) : {};
                    console.log(JSON.stringify(data.data))
                    if (data.code == 200) {
                        if (data.data.indexOf('http') != -1) {
                            imgs.push(data.data);
                            if (imgs.length == (this.temp.tempFilePath.length - this.temp.failNum)) {
                                this.setState({
                                    imgData: imgData.concat(imgs),
                                }, () => {})
                            }
                        } else {
                            this.temp.failNum += 1; //失败张数加1
                            if (imgs.length == (this.temp.tempFilePath.length - this.temp.failNum)) {
                                this.setState({
                                    imgData: imgData.concat(imgs),
                                }, () => {})
                            }
                            unite.showToast(data.data)
                        }
                    } else {
                        this.temp.failNum += 1; //失败张数加1
                        if (imgs.length == (this.temp.tempFilePath.length - this.temp.failNum)) {
                            this.setState({
                                imgData: imgData.concat(imgs),
                            }, () => {})
                        }
                        unite.showToast('图片错误请重新上传')
                    }
                },
                fail: (e) => {
                    console.log(e);
                }
            });
        });
    };

    //删除图片
    deleteImg = (index) => {
        this.setState((pervState) => {
            pervState.imgData.splice(index, 1);
            pervState.imgDataSl.splice(index, 1);
            return {
                imgData: pervState.imgData,
                imgDataSl: pervState.imgDataSl
            };
        });
    };

    //input内容保存
    datum = (name,val) => {
        console.log(val)
        if (name == 'title') {

            this.setState({
                [name]: val.detail.value
            })
        } else {
            this.setState({
                [name]: val
            })
        }
    };

    //添加课程
    addCourse = () => {
        Taro.navigateTo({
            url: '../addCourse/addCourse'
        });
    };

    //定位
    getLoadtion = () => {
        Taro.chooseLocation({
            success: res => {
                if (res.errMsg == 'chooseLocation:ok') {
                    console.log(res);
                    this.setState({
                        loadtion: res
                    })
                } else {
                    unite.showToast('定位失败，请重新定位')
                }
            }
        })
    };

    //发布
    sumbit = () => {
        const {imgData, text, title, loadtion, myCourse} = this.state;
        const {getGainCourse} = this.props;
        if (imgData.length == 0) return unite.showToast('请选择至少一张照片');
        if (!text) return unite.showToast('请输入标题');
        if (!title) return unite.showToast('请输入正文');
        // if (myCourse.length == 0) return unite.showToast('请选择课程');
        // if (loadtion.length == 0) return unite.showToast('请添加地址');
        if(this.temp.isLoading) return;
        this.temp.isLoading = true;
        const params = {
            url: '/momments/publish',
            data:{
                imgUrl: imgData, //图片地址，展示的时候按照存入时候的顺序
                title: text, //动态标题
                content: title,
                address: loadtion.name, //地址
                addressDetail: loadtion.address, //详细地址，如道路、门牌号、小区、楼栋号、单元室等
                latitude: loadtion.latitude, //中心纬度
                longitude: loadtion.longitude, //中心经度
                dispatchId: myCourse.dispatchId, //课程安排id
            }
        };
        request(params).then(res => {
            this.temp.isLoading = false; //防止多次
            if (res) {
                if(res.code == 200) {
                    unite.showToast('发布成功');
                    getGainCourse('');
                    setTimeout(() => {
                        Taro.switchTab({
                            url: '/pages/home/home'
                        })
                    }, 2000)
                }
            }
        })
    };

    render() {
        const {imgData, imgDataSl, text, title, loadtion, myCourse, cWidth, cHeight} = this.state;
        return (
            <View className="page">
                <View className="issue-top-wrap">
                    <View className="issue-img-content flex-l">
                        {imgDataSl && imgDataSl.map((item, index) => (
                            <View className="imgs-wrap" key={index}>
                                <Image className="close-icon" src={Close} onClick={this.deleteImg.bind(this, index)}/>
                                <Image className="imgs" src={item}/>
                            </View>
                        ))}
                        {imgDataSl && imgDataSl.length < 9 &&(
                            <Image className="img-icon" src={ImgAdd} mode="aspectFit" onClick={this.upImgs}/>
                        )}
                    </View>
                    <View className="issue-text-wrap flex-l">
                        <AtInput
                            border={false}
                            className="ins"
                            name='realName'
                            type='text'
                            placeholder='填写标题会有更多赞哦~'
                            value={text}
                            onChange={this.datum.bind(this, 'text')}
                            onBlur={this.datum.bind(this, 'text')}
                            onFocus={this.datum.bind(this, 'text')}
                        />
                    </View>
                    <View className="ins-title-content">
                        {/*<textarea*/}
                        {/*    className="ins-title"*/}
                        {/*    placeholder="添加正文"*/}
                        {/*    bindblur={this.datum.bind(this, 'title')}*/}
                        {/*    bindlinechange={this.datum.bind(this, 'title')}*/}
                        {/*    bindinput={this.datum.bind(this, 'title')}*/}
                        {/*    bindfocus={this.datum.bind(this, 'title')}*/}
                        {/*    onFocus={this.datum.bind(this, 'title')}*/}
                        {/*    onBlur={this.datum.bind(this, 'title')}*/}
                        {/*    maxlength={-1}*/}
                        {/*/>*/}
                        <Textarea
                            textOverflowForbidden={false}
                            value={title}
                            onFocus={this.datum.bind(this, 'title')}
                            onBlur={this.datum.bind(this, 'title')}
                            bindinput={this.datum.bind(this, 'title')}
                            maxlength={-1}
                            placeholder="添加正文"
                        />
                    </View>
                </View>
                <View className="issue-list-wrap">
                    {myCourse && myCourse.length != 0 ? (
                        <View className="issue-list-shop border-bottom flex-lr" onClick={this.addCourse}>
                            <View className="flex-l">
                                <Image className="head-icon" src={myCourse.avatar}/>
                                <View>
                                    <View className="name">{myCourse.className}</View>
                                    <View className="timer">{myCourse.classScaleName}</View>
                                    <View className="flex-l">
                                        {myCourse.labelNames.map((value, is) => (
                                            <View className="biaoqian flex-center" key={is}>{value}</View>
                                        ))}
                                    </View>
                                </View>
                            </View>
                            <View className="flex-r rg-name">
                                <View>重选</View>
                                <Image className="right-two" src={Right1} mode="aspectFit"/>
                            </View>
                        </View>
                    ) : (
                        <View className="issue-list border-bottom flex-lr" onClick={this.addCourse}>
                            <View className="flex-l">
                                <Image className="icons" src={Shop}/>
                                <View>添加课程</View>
                            </View>
                            <Image className="right-icon" src={Right}/>
                        </View>
                    )}
                    {loadtion && loadtion.length != 0 ? (
                        <View className="issue-list-shop flex-lr" onClick={this.getLoadtion}>
                            <View>
                                <View className="names">{loadtion.name}</View>
                                <View className="titles text-overflow">{loadtion.address}</View>
                            </View>
                            <View className="flex-r rg-name">
                                <View>重选</View>
                                <Image className="right-two" src={Right1} mode="aspectFit"/>
                            </View>
                        </View>
                    ) : (
                        <View className="issue-list flex-lr" onClick={this.getLoadtion}>
                            <View className="flex-l">
                                <Image className="icons" src={Address}/>
                                <View>添加地点</View>
                            </View>
                            <Image className="right-icon" src={Right}/>
                        </View>
                    )}
                </View>
                <View className="issue-btns-wrap">
                    <View className="flex-center btns" onClick={this.sumbit}>发布</View>
                </View>
                <Canvas canvasId="myCanvas" style={`width: ${cWidth}px; height: ${cHeight}px; position: fixed; left:-10000px; top:-10000px; z-index: -100`}/>
            </View>
        )
    }
}

const mapStateToProps = state => {
    let {userToken, map, gainCourse} = state;
    return {
        userToken,
        map,
        gainCourse
    }
};

const mapDispatchToProps = {
    getbackPage: actionCreator.getbackPage,
    getGainCourse: actionCreator.getGainCourse,
};

export default connect(mapStateToProps, mapDispatchToProps)(IssuePage);



